" File              : pyHtmlPreviewer.vim
" Author            : yang <mightyang@hotmail.com>
" Date              : 20.12.2019
" Last Modified Date: 20.12.2019
" Last Modified By  : yang <mightyang@hotmail.com>

let g:pyHtmlPreviewerAutoOpen=1
let g:pyHtmlPreviewerAutoOpenFold=1
let g:pyHtmlPreviewerFileType='*.html'
let g:pyHtmlPreviewerPosAtText=1
let s:scriptPath=expand('<sfile>:p:h')
function! PyHtmlPreview()
python3 << EOF
import vim, sys
from PySide2 import QtGui, QtWidgets, QtCore, QtWebEngineWidgets, QtWebChannel, QtXml
from threading import Thread

sys.path.append(vim.eval('s:scriptPath'))

from pyHtmlPreviewer import *

EOF
endfunc

function! PySideApp()
python3 <<EOF
app = QtCore.QCoreApplication.instance()
if app == None:
    app = QtWidgets.QApplication(sys.argv)
    appExists = False

if not appExists:
    t = Thread(target=app.exec_)
    t.setDaemon(True)
    t.start()
EOF
endfun

function! PyHtmlBrowser()
call PyHtmlPreview()
call PySideApp()
python3 <<EOF
if "pyHtmlBrowser" in dir():
    if not pyHtmlBrowser.isVisible():
        pyHtmlBrowser.show()
    pyHtmlBrowser.refreshHtml('BROWSER')

else:
    pyHtmlBrowser = browserMainWindow()
    #pyHtmlBrowser.refreshHtml('BROWSER')
    pyHtmlBrowser.show()
EOF
endfunc

function! PyHtmlPreviewToggle()
python3 << EOF
pyHtmlBrowser.switchVisible()
EOF
endfunc

function! PyHtmlPreviewShow()
python3 << EOF
pyHtmlBrowser.show()
EOF
endfunc

function! PyHtmlPreviewHide()
python3 << EOF
pyHtmlBrowser.hide()
EOF
endfunc

function! PyHtmlPreviewRefresh()
let vimRow = winheight(0)
python3 << EOF
pyHtmlBrowser.refreshHtml('BROWSER')
# pyHtmlBrowser.reScroll()
EOF
endfunc

function! PyHtmlPreviewReScroll()
let vimRow = winheight(0)
python3 << EOF
# pyHtmlBrowser.reScroll()
EOF
endfunc

function! PyHtmlPreviewRePosition()
python3 << EOF
pyHtmlBrowser.rePosition()
EOF
endfunc

function! PyHtmlPreviewWriteHtml(htmlPath)
python3 << EOF
pyHtmlBrowser.writeHtml(vim.eval("a:htmlPath"))
EOF
endfunc

function! PyHtmlPreviewWriteImg(imgPath)
python3 << EOF
pyHtmlBrowser.writeImg(vim.eval("a:imgPath"))
EOF
endfunc

" map <F10> :call PyHtmlPreviewToggle()<CR>
if g:pyHtmlPreviewerAutoOpen
    execute 'autocmd BufWinEnter ' . g:pyHtmlPreviewerFileType . ' nested call PyHtmlBrowser()'
    " execute 'autocmd! TextChanged,TextChangedI ' . g:pyHtmlPreviewerFileType . ' call PyHtmlPreviewRefresh()'
    execute 'autocmd BufWritePost ' . g:pyHtmlPreviewerFileType . ' call PyHtmlPreviewRefresh()'
    " execute 'autocmd BufEnter ' . g:pyHtmlPreviewerFileType . ' call PyHtmlPreviewShow()'
    execute 'autocmd BufLeave ' . g:pyHtmlPreviewerFileType . ' nested call PyHtmlPreviewHide()'
    " autocmd! CursorMoved *.html call PyHtmlPreviewReScroll()
endif
